package com.dhcc.httpserver;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;

import com.dhcc.util.CloseUtil;


public class Dispatcher implements Runnable{

	private Socket client;
	private Request request;
	private Response response;
	private int code=200;
	
	Dispatcher(Socket client){
		this.client = client;
		  // 如果10毫秒还没有数据，则视同没有新的数据了。    
	      // 因为有Keep-Alive的缘故，浏览器可能不主动断开连接的。    
	      // 实际应用，会根据协议第一行是GET还是 POST确定。   
		try {
			client.setSoTimeout(10);
		} catch (SocketException e1) {
			
			return;
		}
		try {
			this.request = new Request(client.getInputStream());
			this.response = new Response(client.getOutputStream());
		} catch (IOException e) {
			code=500;
			return ;
		}
		
	}
	
	
	
	@Override
	public void run() {
	
		
		try {
			
			Servlet servlet = WebApp.getServlet(request.getUrl());
			if (null == servlet) {
				this.code = 404;
			}
			
				try {
					servlet.service(request, response);
				} catch (Exception e) {
					
					this.code=500;
					e.printStackTrace();
				} 
			
			
			response.pushToClient(code);   //推送到客戶端
		} catch (IOException e) {
			
			try {
				response.pushToClient(500);
			} catch (IOException e1) {
			
				e.printStackTrace();
			} 
			
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		CloseUtil.closeAll(client);
	
	}

}
